#include "cc.h"
#include "tcp_client_fun.h"
#include "common_util.h"

TaskHandle_t taskClientHandle = NULL;
// 创建 TCP 客户端
WiFiClient tcp_client;

//是否已经在等待重连
uint8_t rcing = 0;

void TCPClientInit() {
  if (!tcp_client_enable) {
    return;
  }
  xTaskCreate(taskClientTCP, "taskClientTCP", 1024 * 10, NULL, 1, &taskClientHandle);
}

void checkTCPServer() {
  if (tcp_client_enable && !rcing && !tcp_client.connected()) {
    Serial.print("Check disconnected from server ");
    Serial.print(TCPServerIP);
    Serial.print(":");
    Serial.println(TCPServerPort);
    vTaskDelete(taskClientHandle);
    TCPClientInit();
  }
}

uint8_t requestClientTCP(String request, int len) {
  if (!(request.startsWith("NTC_") || request.startsWith("ntc_"))) {
    return 0;
  }
  if (len < 6) {
    return 1;
  }
  uint8_t c4 = request.charAt(4);
  if (c4 == 'a' || c4 == 'A') {
    request = request.substring(5);
    Serial.print("Set new TCP server IP:");
    char* a = strdup(request.c_str());
    saveVlaueStr(TCPServerIP_key, a);
    Serial.println(a);
    free(a);
    return 1;
  }
  if (c4 == 'p' || c4 == 'P') {
    request = request.substring(5);
    uint16_t p = request.toInt();
    if (p == 0) {
      Serial.print("Error port:");
      Serial.println(request);
      Serial.println(p);
      return 1;
    }
    saveVlaueU16(TCPServerPort_key, p);
    Serial.print("Set new TCP server port:");
    Serial.println(p);
    Serial.println(request);
    return 1;
  }
  if (c4 == 'e' || c4 == 'E') {
    Serial.print("Set TCP client:");
    if (request.charAt(5) == '1') {
      saveVlaueU8(tcp_client_enable_key, 1);
      Serial.println("ON");
    } else {
      saveVlaueU8(tcp_client_enable_key, 0);
      Serial.println("OFF");
    }
    return 1;
  }
  return 1;
}
uint8_t firstConn = 1;
void taskClientTCP(void* ptParam) {
  while (true) {
    rcing = 0;
    if (firstConn) {
      firstConn = 0;
      //这个tcp_client.connect第一次连接TCP服务器必须失败。
      //如果第一次连接就连接成功。那么后面TCP服务器关机后（TCP连接被迫断开）。
      //这边的tcp_client.connected()永远返回1。导致无法重连TCP服务器。
      //也不知道这是谁的毛病。
      tcp_client.connect("bheqh", 0, tcp_timeout_ms);
      continue;
    }
    Serial.print("Now Connected to TCP server ");
    Serial.print(TCPServerIP);
    Serial.print(":");
    Serial.println(TCPServerPort);
    // 连接到服务器
    if (tcp_client.connect(TCPServerIP, TCPServerPort, tcp_timeout_ms)) {
      Serial.println("Connected to TCP server ok!");
      while (true) {
        if (tcp_client.connected()) {
          if (tcp_client.available()) {
            String request = tcp_client.readStringUntil('\n');
            if (!requestTest(request)) {
              continue;
            }
            requestString(request);
            if (transmit) {
              Serial.println(request);
              for (uint8_t i = 0; i < MAX_TCP_CLIENTS; i++) {
                if (serverClients[i] && serverClients[i].connected()) {
                  serverClients[i].println(request);
                }
              }
            }
          }
        } else {
          Serial.print("Disconnected from server ");
          Serial.print(TCPServerIP);
          Serial.print(":");
          Serial.println(TCPServerPort);
          tcp_client.stop();  // 断开连接
          break;
        }
      }
    } else {
      Serial.print("Connection to server ");
      Serial.print(TCPServerIP);
      Serial.print(":");
      Serial.print(TCPServerPort);
      Serial.println(" failed");
    }
    rcing = 1;
    for (uint8_t i = 30; i > 0; i--) {
      if (i % 5 == 0) {
        Serial.print(i);
        Serial.println("s ReConnected to TCP server");
      }
      delay(1000);
    }
  }
}